import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from "@/store"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "about" */ '../views/Goods.vue')
  },
  {
    path: '/order',
    name: 'order',
    // 路由独享守卫
    beforeEnter: (to, from, next) => {
      console.log(to, from);  // 路由对象
      let token = localStorage.getItem("x-auth-token")
      console.log("/order独享守卫的：", token);
      if (!token) {
        // alert("请先登录")
        store.dispatch("showToast/asyncShowToast", {
          isShow: true,
          msg: "请先登录!",
          type: "warning",
        })
        // 触发 mutations 方法，弹出登录框
        store.commit("showLoginModel/changeIsShowLoginModel", true)
        return
      }
      next()
    },
    component: () => import(/* webpackChunkName: "about" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "about" */ '../views/Free.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect: "/user/cart",
    component: () => import(/* webpackChunkName: "about" */ '../views/User.vue'),
    children: [
      {
        path: "cart",
        component: () => import(/* webpackChunkName: "about" */ '@/components/user/Cart.vue'),
      },
    ]
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../components/Details.vue')
  },
  {
    path: '/expand',
    name: 'expand',
    component: () => import('../views/VueExpand.vue')
  },
  {
    path: '*',
    name: '*',
    component: () => import('../components/404Item.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

// 全局前置守卫  注释要全注释掉，或者留个 next()
/* router.beforeEach((to, from, next) => {
  // console.log(to, from);  // 路由对象
  if (to.path == "/user") {
    let token = localStorage.getItem("x-auth-token")
    console.log("全局前置守卫：", token);
    if (!token) {
      // alert("请先登录")
      store.dispatch("showToast/asyncShowToast", {
        isShow: true,
        msg: "请先登录!",
        type: "warning",
      })
      return
    }
    next()
  } else {
    next()
  }
}) */

export default router
